<?php

function init_db_random_map_info(){
  //初始化数据库
  if(!get_data("SHOW TABLES LIKE 'random_map_info'")){
      
      run_sql("
          CREATE TABLE IF NOT EXISTS `random_map_info` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `title` char(50) NOT NULL,
            `code` char(32) NOT NULL ,
            `is_his` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=his',
            `category` int(11) unsigned NOT NULL COMMENT '',
            `ud1` char(32) NOT NULL,
            `ud2` char(32) NOT NULL,
            `ud3` char(32) NOT NULL,
            `ud4` char(32) NOT NULL,
            `ud5` char(32) NOT NULL,
            `ud6` char(32) NOT NULL,
            `ud7` char(32) NOT NULL,
            `ud8` char(32) NOT NULL,
            `ud9` char(32) NOT NULL,
            `create_date` char(20) NOT NULL,
            `modify_date` char(20) NOT NULL,
            `admin_uid` char(20) NOT NULL,
            `owner_uid` char(20) NOT NULL,
            `json_text` text NOT NULL,
            `parent_id` int(11) unsigned NOT NULL DEFAULT '0',
            `sort` tinyint(4) unsigned NOT NULL DEFAULT '99',
            PRIMARY KEY (`id`)
          ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
      ");

    run_sql("
      ALTER TABLE  `random_map_info` ADD UNIQUE (`code`)
    ");

  }
}


function set_age_for_random_map_info($map_uuid,$age=0){
  $tmp_sql=<<<SQL
UPDATE `random_map_info` SET `parent_id`=?i , `modify_date`=?s , `ud2`=?s WHERE `code`=?s
SQL;
  
  $cf_now = date('Y-m-d H:i:s');
  if($age===0){
    //长期有效
    $tmp_sql = prepare($tmp_sql ,array(2,$cf_now, 0,$map_uuid) );
  }else{
    //有效期为 intval($age) 天
    $tmp_sql = prepare($tmp_sql ,array(3,$cf_now, intval($age),$map_uuid) );
  }
    return run_sql($tmp_sql);
}


function get_city_pic($n=null){
  $city_pic_arr=array();
  array_push($city_pic_arr, array('top_left' =>105 , 'top_right' =>106 ,'foot_left' =>121 , 'foot_right' =>122));
  array_push($city_pic_arr, array('top_left' =>107 , 'top_right' =>109 ,'foot_left' =>123 , 'foot_right' =>124));
  array_push($city_pic_arr, array('top_left' =>109 , 'top_right' =>110 ,'foot_left' =>125 , 'foot_right' =>126));
  array_push($city_pic_arr, array('top_left' =>111 , 'top_right' =>112 ,'foot_left' =>127 , 'foot_right' =>128));

  array_push($city_pic_arr, array('top_left' =>137 , 'top_right' =>138 ,'foot_left' =>153 , 'foot_right' =>154));
  array_push($city_pic_arr, array('top_left' =>139 , 'top_right' =>140 ,'foot_left' =>155 , 'foot_right' =>156));
  if($n!==null && isset($city_pic_arr[$n])){
    return $city_pic_arr[$n];
  }
  return _rnd(0,count($city_pic_arr)-1);
}

function get_village_pic($n=null){
  $pic_arr=array();
  array_push($pic_arr, array('top_left' =>169 , 'top_right' =>170));
  array_push($pic_arr, array('top_left' =>171 , 'top_right' =>172 ));
  array_push($pic_arr, array('top_left' =>173 , 'top_right' =>174 ));
  array_push($pic_arr, array('top_left' =>187 , 'top_right' =>188 ));
  array_push($pic_arr, array('top_left' =>189 , 'top_right' =>190 ));

  if($n===null) $n = _rnd(0,count($pic_arr)-1);
  if(isset($pic_arr[$n])){
    return $pic_arr[$n];
  }
  return $pic_arr[0];
}

function get_smaill_village_pic($n=null){
  $pic_arr=array();
  array_push($pic_arr, array('top_left' =>185 , 'top_right' =>0));
  array_push($pic_arr, array('top_left' =>186 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>175 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>191 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>187 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>188 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>189 , 'top_right' =>0 ));
  array_push($pic_arr, array('top_left' =>190 , 'top_right' =>0 ));

  if($n===null) $n = _rnd(0,count($pic_arr)-1);
  if(isset($pic_arr[$n])){
    return $pic_arr[$n];
  }
  return $pic_arr[0];
}



//画地图
function map_div($x, $y, $v){
    global $w, $h, $path;

    $rd = 149;

    //if ( $y > 4 ) $v = 0;
    $k = $y * $w + $x;
    //if ( array_key_exists($k, $this->_enable) ) {
        //echo "<div class=\"grid cell_enable_{$this->_enable[$k]}\" style=\"";
    //} else {
        echo "<div class=\"grid tileBpic ";
        if($v==='*') {
            //70%是草地,其他事花朵
            $catArr=array(161,162,163,164,177,178,179,180,216,232,243);
            $jj = _rnd(0,100);
            if($jj<70){
                $tt = 2;
            }else{
                $tt = _rnd(0,count($catArr)-1);
            }            
            echo 'tileBpic_'.$catArr[$tt];
        }else{
            $catArr=array(89,181,168,184);  //树,枯木,石,矿
            $jj = _rnd(0,100);
            if($jj<90){
                $tt = 0;
            }else if($jj<95){
                $tt = 1;
            }else{                
                $tt = _rnd(0,count($catArr)-1);
            }
            echo 'tileBpic_'.$catArr[$tt];
        }        
        echo "\" style=\"";
    //}
    echo 'top:'. 35*$y.'px;';
    echo 'left:'. 35*$x.'px;';
    //if ($v & 1)
        //echo "border-top:1px solid #F5F5F5;";
    //if ($v & 2)
        //echo "border-right:1px solid #F5F5F5;";
    //if ($v & 4)
        //echo "border-bottom:solid 1px #F5F5F5;";
    //if ($v & 8)
        //echo "border-left:solid 1px #F5F5F5;";
    if ( in_array($y * $w + $x, $path) )
        echo "color:red;";
    echo '">';
    // echo $y * $w + $x;
    // if($v==='*') {
    //     echo '.';
    //     //163
    // }else{
    //     echo '#';
    //     //89
    // }
    echo '</div>'."\n";
}

//画地图
function div2($x, $y, $v){
    global $w, $h, $path;
    //if ( $y > 4 ) $v = 0;
    $k = $y * $w + $x;
    //if ( array_key_exists($k, $this->_enable) ) {
        //echo "<div class=\"grid cell_enable_{$this->_enable[$k]}\" style=\"";
    //} else {
        echo "<div class=\"grid \" style=\"";
    //}
    echo 'top:'. 10*$y.'px;';
    echo 'left:'. 10*$x.'px;';
    //if ($v & 1)
        //echo "border-top:1px solid #F5F5F5;";
    //if ($v & 2)
        //echo "border-right:1px solid #F5F5F5;";
    //if ($v & 4)
        //echo "border-bottom:solid 1px #F5F5F5;";
    //if ($v & 8)
        //echo "border-left:solid 1px #F5F5F5;";
    if ( in_array($y * $w + $x, $path) )
        echo "color:red;";
    echo '">';
    // echo $y * $w + $x;
    if($v==='*') {
        echo '.';
        //163
    }else{
        echo '#';
        //89
    }
    echo '</div>'."\n";
}

function isInRoadArr($k,$roadpath){
    if($roadpath && is_array($roadpath)){
        foreach($roadpath as $roadSetId=>$roadSetArr){
            if(is_array($roadSetArr)){
                if ( in_array($k, $roadSetArr) ){
                    // return $roadSetId;
                    return array('id'=>$roadSetId,'title'=>$roadSetArr[0]);
                    // break;
                }    
            }else{
                if($k === $roadSetArr){
                    return array('id'=>$roadSetId,'title'=>$roadSetArr[0]);
                }
            }
            
        }    
    }    
    return false;
}


function get_base_color_arr(){
  $colorArr=array('#666666','#66CCCC','#CCFF66','#FF99CC','#FFCC00','#009999','#CC3333','#666699','#CCFF99','#FF9900');
  $len = count($colorArr);
  $first_color=$colorArr[_rnd(0,$len-1)];
  $ret=array($first_color);
  foreach ($colorArr as $cc) {
    if($cc !==$first_color){
      $ret[] = $cc;
    }
  }
  return $ret;
}

$base_color_arr=null;

// 画随机地图方法
function map_div_debug($x, $y, $v){  
  global $w, $h, $path, $roadpath;
  global $base_color_arr;

  if($base_color_arr==null){
    $base_color_arr = get_base_color_arr();
  }

  $ret_html = '';

  $k = $y * $w + $x;
  $roadSetId=isInRoadArr($k,$roadpath);
  $nodeSetID=false;
  $len = count($path);
  foreach ($path as $tmpid=>$tmpArr) {
    if ($tmpArr)
    if ( in_array($k, $tmpArr) ){
      $nodeSetID=$tmpid;
      break;
    }
  }
  $div_id = 'div_'.$x.'_'.$y;
  if($roadSetId!==false){
    $ret_html .= "<div id=\"".$div_id."\" class=\"grid  \" style=\"";
  }else{
    $ret_html .= "<div id=\"".$div_id."\"class=\"grid cell_{$v}\" style=\"";
  }

  $ret_html .= 'top:'. 34*$y.'px;';
  $ret_html .= 'left:'. 34*$x.'px;';

  //echo '/* k:'.$k.' */';
  $inNodeSetFlag=false;
  $len = count($path);
  $colorArr=$base_color_arr;
  foreach ($path as $tmpid=>$tmpArr) {
    if ($tmpArr)
    if ( in_array($k, $tmpArr) ){      
      $id = fmod(intval($tmpid),count($colorArr));
      $ret_html .= "background-color:".$colorArr[$id].';';
      $inNodeSetFlag=true;
      break;
    }
  }
  if($inNodeSetFlag===false){
    if ( in_array($k, $roadpath) ){
      $ret_html .= 'background-color:#CCCCCC;';
    }
  }
  $ret_html .= '">';
  if($inNodeSetFlag===false && $roadSetId!==false){
    $tmpHtml='R:'.$roadSetId['id'];
    // $tmpHtml=$k;
    $tmpTitle = '#'.$k."\n".$roadSetId['title']."\n".'rd:'.$roadSetId['id'];
    $ret_html .= '<a href="javascript:void(0);" title="'.$tmpTitle.'">'.$tmpHtml.'</a>';
  }else{
    $ret_html .= $k;
  }
  // echo $y * $w + $x;
  // echo $v;
  $ret_html .= '</div>'."\n";
  return $ret_html;
}


function gen_new_map(){
	global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
	global $debugMode, $time_log;

  $max = 1000;
	$tt = intval(v('w'))  ;
    if ($tt>0 && $tt<=$max){
        $w=$tt;
    }else{
        die('403 Access Denied/Forbidden');
    }

    $tt = intval(v('h'))  ;
    if ($tt>0 && $tt<=$max){
        $h=$tt;
    }else{
        die('403 Access Denied/Forbidden');
    }


    //初始化数据库
    init_db_random_map_info();

    $tt = intval(v('d'))  ;
    if ($tt>0 && $tt<100){
        $density=$tt;
    }

    $ksRndMap = new kisRandomMap();
    $aStar = new AStar();

    $endId = ($w * $h)-1;

    // $time_log.= "基础加载时间: ". used_time($pagestartime) ."秒.<br/>".PHP_EOL; 
    $time1=microtime(); 

    $ksRndMap->set($w, $h);
    $ksRndMap->create();
    // $grids = $ksRndMap->get();
    $ksRndMap->setDensity($density);
    // $ksRndMap->setCA(4,5);
    $ksRndMap->run_ca();

    if($debugMode) $ksRndMap->set_debug(1);
    if($debugMode) echo '<!--';
    $tmpNodeSet=$ksRndMap->debug_walk();
    $grids = $ksRndMap->get();
    // var_dump($grids);
    $baseNodeSet=$ksRndMap->debug_nodeSet();
    if($debugMode) echo '-->';
    $time_log.= "maze->create 时间: ". used_time($time1) ."秒.<br/>".PHP_EOL; 
    $time2=microtime(); 

    // $path=$tmpNodeSet;
    $path=array();
    $roadpath=array();
    foreach ($baseNodeSet as $value) {
        array_push($path,$value);
    }

    // 寻路
    $aStar->set($w, $h, $grids);
    // $path = $aStar->search(0, $endId);       // 从零开始找到35
    $roadArr=$ksRndMap->get_road();
    // var_dump($roadArr);
    foreach ($roadArr as $road) {
        $roadInfo=$ksRndMap->getRoadByNodeSet($road['from'],$road['to'],$baseNodeSet);
        $pos1 = $roadInfo['from'];
        $pos2 = $roadInfo['to'];
        $tmpPath=array();
        $tmpPath = $aStar->search($pos1, $pos2);
        // if($debugMode) {
        //     echo '--path array,#'.$pos1.'-#'.$pos2.':'.implode(',',$tmpPath) .PHP_EOL.PHP_EOL.PHP_EOL; 
        // }
        $tmpPath2=array();
        array_push($tmpPath2,'road_'.$pos1.'_'.$pos2);
        foreach ($tmpPath as $roadPos) {
            if($roadPos!==$pos1 && $roadPos!==$pos2){
                array_push($tmpPath2,$roadPos);
            }
        }
        $tmpPath2 = fix_roadPath($tmpPath2);
        array_push($roadpath,$tmpPath2);    
    }
    //array_push($path,$roadpath);
    // var_dump($roadpath);
    $time_log.= "aStar->search 时间: ". used_time($time2) ."秒.<br/>".PHP_EOL; 

    $mapJson = array();
    $mapJson['map'] = $ksRndMap->getMapJsonObj();
    $mapJson['road'] = $roadpath;
    $mapJson['path'] = $path;

    return $mapJson;
}

function save_random_map_info($mapJson,$code,$options_arr=null){
	global $debugMode, $time_log;
    //REPLACE INTO
    //INSERT INTO
    $tmp_sql=<<<SQL
INSERT INTO `random_map_info`( `title`, `code`, `is_his`, `category`, 
    `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9`,
    `create_date`, `modify_date`, `admin_uid`, `owner_uid`, `json_text`, `parent_id`, `sort`)
     VALUES (?s,?s,?i,?s,   ?s,?s,?s,?s,?s,?s,?s,?s,?s,    ?s,?s,?s,?s,?s,?i,?i )
SQL;
    $cf_now = date('Y-m-d H:i:s');
    
    $opt_arr=array(
        'ud1'=>''       //存储格式，是否是压缩的
        ,'ud2'=>''      //有效期天数      
        ,'ud3'=>'0'      //地图格式  1=地牢
        ,'ud4'=>''      //地图大小
        ,'ud5'=>''
        ,'ud6'=>''
        ,'ud7'=>''
        ,'ud8'=>''
        ,'ud9'=>'');

    if($options_arr && is_array($options_arr)){
        foreach ($options_arr as $key => $value) {
            $opt_arr[$key]=$value;
        }   
    }

    $json_text = json_encode($mapJson);
    $len_source = max_len($json_text);
    $len_gzcompress = 0;
    if($len_source>500){
        $opt_arr['ud1']=1;
        $json_text = gzcompress($json_text,9);
        $json_text = urlencode($json_text);
        $len_gzcompress = max_len($json_text);
    }    
    $json_text = addslashes( $json_text ); 

    // if($debugMode) 
    //     echo '<br/>$$$$ '.$row_data.PHP_EOL;

    $tmp_sql = prepare($tmp_sql ,array($code, $code, 0, 'tmp',
        $opt_arr['ud1'], $opt_arr['ud2'], $opt_arr['ud3'], $opt_arr['ud4'], $opt_arr['ud5'], 
            $opt_arr['ud6'], $opt_arr['ud7'], $opt_arr['ud8'], $opt_arr['ud9'],
        $cf_now , $cf_now,'admin', 'admin', $json_text,1,1
        ) );

    if($debugMode){
        // echo '<br/>-- '.$tmp_sql.PHP_EOL;
        $time_log .= 'len_source='.$len_source.PHP_EOL;
        $time_log .= 'len_gzcompress='.$len_gzcompress.PHP_EOL;

        if($len_gzcompress) {
            $tt1 = $len_source-$len_gzcompress;
            $tt2 = $tt1 / $len_source ; 
            $time_log .= 'save :'.$tt1.'B, '.$tt2.'%'.PHP_EOL;
        }
    }

    return run_sql($tmp_sql);	
}


function reload_map($map_uuid){
	global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
	global $debugMode, $time_log;


  //初始化数据库
  init_db_random_map_info();

  $tmp_sql=<<<SQL
SELECT * FROM `random_map_info` WHERE `code`=?s AND `is_his`=?i 
SQL;
    $tmp_sql = prepare($tmp_sql ,array($map_uuid, 0) );

    // if($debugMode) echo '<br/>-- '.$tmp_sql.PHP_EOL;

    $ret =get_data($tmp_sql);

    if(!isset($ret['map'])) $ret = $ret[0];
    // var_dump($ret);

    if(isset($ret['parent_id']) && isset($ret['create_date']) && isset($ret['modify_date']) ){
        if(intval($ret['parent_id'])==1 ){   //临时
            set_age_for_random_map_info($map_uuid,7);  //非临时，有效期为15 day

        }else if (intval($ret['parent_id'])==2 ){    //长期有效
            //skip
        }else{
            $cd = $ret['create_date'];
            $md = $ret['modify_date'];
            $cf_now = date('Y-m-d H:i:s');  //2014-11-10 15:18:32

            // 判断是否大于30分钟 (1800秒)
            if( strtotime($cf_now) - strtotime($md) > 1800 ){   
                //初次修改后，超过30分钟，再修改
                if(intval($ret['parent_id'])==3 && substr($cd, 0,10)!=substr($md, 0,10) ) {
                    set_age_for_random_map_info($map_uuid,90);
                }else{
                    set_age_for_random_map_info($map_uuid,15);
                }
            }
        } 
    }    

    $ksRndMap = new kisRandomMap();
    $aStar = new AStar();
    
    // var_dump($ret['json_text']);
    // $json = safe_json_str_decode($ret['json_text']);
    $json = stripslashes($ret['json_text']);
    if(trim($ret['ud1'])=='1'){
        $json=urldecode($json);
        $json=gzuncompress($json);
    }
    // var_dump($json);
    // echo '=========================='.PHP_EOL;
    // $jsonObj = json_decode($ret['json_text']);
    // var_dump($jsonObj);

    $jsonObj = json_decode($json,true);
    // var_dump($jsonObj);

    if(trim($ret['ud3'])=='1'){
      //dungeon
      // $jsonObj = fix_dungeon_map_for_reload($ret,$jsonObj);
    }

    $map = $ksRndMap->recoveryMap($jsonObj['map']);
    // var_dump($map);
    $w = $map['_w'];
    $h = $map['_h'];
    $density = $map['_density'];
    $grids = $map['_grids'];   

    $path=array();
    $path = $jsonObj['path'];
    $roadpath = $jsonObj['road'];

    // // var_dump($roadpath);
    // $tmpPath = $roadpath[count($roadpath)-1];
    // // var_dump($tmpPath);
    // $tmpPath = fix_roadPath($tmpPath);
    // // var_dump($tmpPath);
    $roadpathNew=array();
    for ($i=0; $i <count($roadpath); $i++) { 
        array_push($roadpathNew,fix_roadPath($roadpath[$i]));
    }
    // array_push($roadpathNew,$tmpPath);
    $roadpath=$roadpathNew;
    $roadpathNew=null;
    // // var_dump($roadpath);

    // var_dump($path);
    $baseNodeSet = $map['_nodeSet'];
    $tmpNodeSet = $map['_nodeTmpSet'];
    // var_dump($baseNodeSet);
    // var_dump($tmpNodeSet);
}

function check_pos_top_val_in_check_arr($v,$val){
    $arr = explode(';', $v);
    $check = explode(';', $val);

  foreach ($arr as $key => $value) {
    if(stripos($value, '#')!==false){
      $arr2 = explode('#', $value);
      $cc = $arr2[count($arr2)-1];
      foreach ($check as $checkvalue) {
          if($cc===$checkvalue) return true;
      }      
    }
  }
  return false;
}

function convert_map_grids($grids,$w ,$h,$color_config){
    $debugMode = get_func_debug_mode(__METHOD__);
    if($debugMode) {
        echo 'DEBUG: ' . __METHOD__ . '()'. PHP_EOL; 
        echo print_r($grids,true);
    }

    // $color_config = array('leaf'=>'5','room'=>'1','hall'=>'1','base'=>'5');
    // $color_config['sort'] = 'hall;room;leaf;base';
    $check = $color_config['room'] . ';' . $color_config['hall'];
    $ret_arr = array();
    for($y = 0; $y < $h; $y++ ){
        for($x=0; $x < $w; $x++ ){
            $v = $grids[$y * $w + $x];
            if(check_pos_top_val_in_check_arr($v,$check)){
                $grids[$y * $w + $x] = '*';
            }else{
                $grids[$y * $w + $x] = 0;
            }
        }
    }

    if($debugMode) {
        echo 'DEBUG: ' . __METHOD__ . '() process end .'. PHP_EOL; 
        echo print_r($grids,true);
    }
    return $grids;
}

// function fix_dungeon_map_for_reload(&$ret,$jsonObj){
//     $debugMode = get_func_debug_mode(__METHOD__);
//     if($debugMode) {
//         echo 'DEBUG: ' . __METHOD__ . '()'. PHP_EOL; 
//         echo print_r($ret,true);
//         echo print_r($jsonObj,true);
//     }
// }

function gen_show_html($pagestartime,$is_dungeon=0){
    global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
    global $debugMode, $time_log;

    $map_html='';
    for($y = 0; $y < $h; $y++ ){
        for($x=0; $x < $w; $x++ ){
            $v = $grids[$y * $w + $x];
            if($debugMode) {
              $map_html .= map_div_debug($x, $y, $v, $is_dungeon);
            }else{
              $map_html .= map_div($x, $y, $v, $is_dungeon);
            }
        }
    }

    $time_log.= "页面运行时间: ". used_time($pagestartime) ."秒.<br/>".PHP_EOL; 

    return $map_html;
}


function debug_showNodeSetInfo(){
	global $debugMode, $baseNodeSet, $tmpNodeSet;
	if(!$debugMode) return '';

	$ret = '';
    $ret .= '<!--'.PHP_EOL;
    if(is_array($baseNodeSet)){
        foreach ($baseNodeSet as $tmpSetId => $tmpSetArr) {
            if(is_array($tmpSetArr)){
                $ret .= '#'.$tmpSetId.'='.implode(',',$tmpSetArr) .PHP_EOL;    
            }else{
                $ret .= '#'.$tmpSetId.'='.$tmpSetArr .PHP_EOL;
            }
        }
        $ret .= '========================================='.PHP_EOL;
    }	    
    if(is_array($tmpNodeSet)){
        foreach ($tmpNodeSet as $tmpSetId2 => $tmpSetArr2) {
            if(is_array($tmpSetArr2)){
                $ret .= '#'.$tmpSetId2.'='.implode(',',$tmpSetArr2) .PHP_EOL;
            }else{
                $ret .= '#'.$tmpSetId2.'='.$tmpSetArr2 .PHP_EOL;
            }  
        }
    }	    
    $ret .= '-->'.PHP_EOL;

	return $ret;
}


function fix_roadPath($tmpPath){        
    return $tmpPath;        //FIXME @141111

    global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
    global $debugMode, $time_log;
    $tmpPathNew = array();
/*
1，非直线
*/
    // var_dump($tmpPath);
    $l = count($tmpPath);
    if($l<6) {
        // if($debugMode){
        //     echo 'DEBUG: '.__FUNCTION__.'()  road len='.$l.PHP_EOL;
        // }
        return sort($tmpPath);
    }

    $fixTimes=0;
    $lastFixId=null;
    for ($i=3; $i <$l; $i++) {         
        if($fixTimes==0 && $tmpPath[$i]==$tmpPath[$i-1]+1 && $tmpPath[$i]==$tmpPath[$i-2]+2 && $tmpPath[$i]==$tmpPath[$i-3]+3){
            //当前为横排第四个
            // if($debugMode){
            //     echo 'DEBUG: '.__FUNCTION__.'() #'.$tmpPath[$i].'<br/>'.PHP_EOL;
            // }
            $jj = _rnd(1,100);
            if($jj<45){
                if($debugMode){
                    echo 'DEBUG: '.__FUNCTION__.'() #'.$tmpPath[$i].'<br/>'.PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1#'.($tmpPath[$i]+$w).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1#'.($tmpPath[$i]+$w-1).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1#'.($tmpPath[$i]+$w-2).'<br/>'.PHP_EOL;
                }
                array_push($tmpPathNew,$tmpPath[$i]+$w);
                array_push($tmpPathNew,$tmpPath[$i]+$w-1);
                array_push($tmpPathNew,$tmpPath[$i]+$w-2);
                $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-1);
                $fixTimes++;

                $arrkey = array_search(($tmpPath[$i]-3), $tmpPathNew);
                if($debugMode){
                    echo 'DEBUG: '.__FUNCTION__.'() mode 1# check'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                }
                if ($arrkey !== false){
                    if($debugMode){
                        echo 'DEBUG: '.__FUNCTION__.'() mode 1# exist'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 1# del'.($tmpPath[$i]-2).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 1# del'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                    }
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-2);
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-3);
                }

            }else if($jj<75){
                if($debugMode){
                    echo 'DEBUG: '.__FUNCTION__.'() #'.$tmpPath[$i].'<br/>'.PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 2# add'.($tmpPath[$i]-$w).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 2# add'.($tmpPath[$i]-$w-1).PHP_EOL;
                    echo 'DEBUG: '.__FUNCTION__.'() mode 2# add'.($tmpPath[$i]-$w-2).'<br/>'.PHP_EOL;                    
                }
                array_push($tmpPathNew,$tmpPath[$i]-$w);
                array_push($tmpPathNew,$tmpPath[$i]-$w-1);
                array_push($tmpPathNew,$tmpPath[$i]-$w-2);
                $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-1);
                $fixTimes++;

                $arrkey = array_search(($tmpPath[$i]-$w-3), $tmpPathNew);
                if ($arrkey !== false){
                    if($debugMode){
                        echo 'DEBUG: '.__FUNCTION__.'() mode 2# exist'.($tmpPath[$i]-$w-3).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 2# del'.($tmpPath[$i]-2).'<br/>'.PHP_EOL;
                        echo 'DEBUG: '.__FUNCTION__.'() mode 2# del'.($tmpPath[$i]-3).'<br/>'.PHP_EOL;
                    }
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-2);
                    $tmpPathNew=arr_del($tmpPathNew,$tmpPath[$i]-3);
                }

            }
            $lastFixId=$i;
            array_push($tmpPathNew,$tmpPath[$i]);
 
        }else{
            if($lastFixId && $i-$lastFixId>5) {
                $fixTimes=0;
                $lastFixId=null;
            }
            array_push($tmpPathNew,$tmpPath[$i]);
        }
    }
    

    // $tmpId=0;
    // $lastArr = array();
    // foreach ($tmpPath as $path_key => $path_value) {
    //     $flag = false;
    //     $tmpArr = array();
    //     $tmpArr['x'] = $ksRndMap->getNodeX($path_value);
    //     $tmpArr['y'] = $ksRndMap->getNodeY($path_value);
    //     $lastArr[$path_key] = $tmpArr;

        // if(!isset($lastArr['x'])) {
        //     $lastArr['x'] = $ksRndMap->getNodeX($path_value);
        //     $lastArr['x_count'] = 0;
        // }else{
        //     $tt = $ksRndMap->getNodeX($path_value);
        //     if($lastArr['x']==$tt){
        //         $lastArr['x_count'] = $lastArr['x_count']+1;
        //         $lastArr['y_count'] = 0; 
        //         $flag = true;
        //     }else{
        //         $lastArr['x'] = $tt;
        //         $lastArr['x_count'] = 0;  
        //     }
        // }
        // if(!$flag){
        //     if(!isset($lastArr['y'])) {
        //         $lastArr['y'] = $ksRndMap->getNodeY($path_value);
        //         $lastArr['y_count'] = 0;
        //     }else{
        //         $tt = $ksRndMap->getNodeY($path_value);
        //         if($lastArr['y']==$tt){
        //             $lastArr['y_count'] = $lastArr['y_count']+1;
        //             $lastArr['x_count'] = 0; 
        //         }else{
        //             $lastArr['y'] = $tt;
        //             $lastArr['y_count'] = 0;  
        //         }
        //     }
        // }
    // }

    // $last=array();
    // foreach ($lastArr as $key => $value) {
    //     if()
    // }
    return $tmpPathNew;
}



function get_search_result_json($table_name,$id,$where,$limit,$offset,$fields_str){
    global $debugMode, $time_log;
/*
{
    "data" : 128,
    "rows" : [{
            "realm" : "",
            "username" : "8614548144271",
            ...
            "acctStopDelay" : 0
        }, {
            ...
        }
    ],
    "success" : true
}
*/
    
    $data= array('data'=>0,'success'=>false,'rows'=>array());

    $tmp_sql = hp_mysql_count_sql($table_name,$where);

    $tmp_arr=get_data($tmp_sql);
    if($tmp_arr===false){
        if($debugMode) echo 'DEBUG: ' . __FUNCTION__ . '() MySQL Error ! ' . $tmp_sql . PHP_EOL;
        return $data;
    }
    if(isset($tmp_arr[0]['num'])){
        $tmp = intval($tmp_arr[0]['num']);
        if($tmp>0){
            $data['data'] = $tmp;
        }
    }

    $tmp_sql = high_performance_mysql_limit_sql($table_name,$id,$where,$limit,$offset,$fields_str);

    $ret =get_data($tmp_sql);
    if($ret===false){
        if($debugMode) echo 'DEBUG: ' . __FUNCTION__ . '() MySQL Error ! ' . $tmp_sql . PHP_EOL;
        return $data;
    }
    $data['success']=true;
    foreach ($ret as $key => $value) {
        $data['rows'][$key]=$value;
    }
    return $data;
}

function show_all_link($only_dungeon=false){
    global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
    global $limit, $offset;
    global $debugMode, $time_log;

/*
SELECT `id`, `title`, `code`, `is_his`, `category`, `ud1`, `ud2`, `ud3`, `ud4`, `ud5`, `ud6`, `ud7`, `ud8`, `ud9`, `create_date`, `modify_date`, `admin_uid`, `owner_uid`, `json_text`, `parent_id`, `sort` FROM `random_map_info`
*/
    $table_name = '`random_map_info`';
    $id = 'id' ;
    // $limit = 0;
    // $offset = 15;
    $fields_str = '`id`,`code`, `is_his`, `ud2`, `ud3`, `ud4`, `create_date`, `modify_date`';

    if($only_dungeon===false){
        $where = ' WHERE `is_his`=?i AND ( `parent_id`=?i OR (`parent_id`=?i AND `ud2`>=?i ))  ORDER BY  `modify_date` DESC ';
        $where = prepare($where ,array(0,2,3,0) );
    }else{
        $where = ' WHERE `is_his`=?i AND `ud3`=?s AND ( `parent_id`=?i OR (`parent_id`=?i AND `ud2`>=?i ))  ORDER BY  `modify_date` DESC ';
        $where = prepare($where ,array(0,$only_dungeon,2,3,0) );
    }

    // echo 'DEBUG: ' . __FUNCTION__ . '() where=' . $where . PHP_EOL;
    // echo 'DEBUG: ' . __FUNCTION__ . '() limit=' . $limit . PHP_EOL;
    // echo 'DEBUG: ' . __FUNCTION__ . '() offset=' . $offset . PHP_EOL;
    $ret_data = get_search_result_json($table_name,$id,$where,$limit,$offset,$fields_str);

    // if(isset($ret_data['success']) && $ret_data['success']){
    //     foreach ($ret_data as $key => $value) {
    //         if(isset($value['ud3'])){
    //           if($value['ud3']==1){
    //             $ret_data[$key]['ud3']='随机地牢';
    //           }else{
    //             $ret_data[$key]['ud3']='随机地图';
    //           }                  
    //         }
    //     }    
    // }
    $json = json_encode($ret_data);
    
    return $json;
}



function debug_map_part($x1,$y1,$w1,$h1,$output=1,$ccid=false){
    global $ksRndMap, $aStar, $w ,$h;
    global $debugMode, $time_log , $grids, $map_html_debug;

    echo 'DEBUG: ' . __FUNCTION__ . '(x1='.$x1.',y1='.$y1.',w1='.$w1.',h1='.$h1.')<br/>'.PHP_EOL;   
    $cc = get_color($ccid);

    echo 'DEBUG: ' . __FUNCTION__ . '() w='.$w.',h='.$h.',output='.$output.',ccid='.$ccid.'<br/>'.PHP_EOL;

    $ret_html = '';

    // $ret_html .= debug_map_html($grids);

    for ($iy=0; $iy < $h1 ; $iy++) { 
      for ($ix=0; $ix <$w1 ; $ix++) { 
          
        $pos = ($y1+$iy) * $w + $x1+$ix;
        // echo 'ix='.$ix.',iy='.$iy.',pos='.$pos.'<br/>'.PHP_EOL;
        // if(isset($grids[$pos])){
            $grids[$pos] = $pos.'#'.$cc;

        // }else{
          // echo 'miss ' . $pos;
          // while ( $pos<= count($grids)) {
          //   $grids[]=0;
          // }
          // $grids[$pos] = $pos;
        // }
      }
    }

    if($output){
      $ret_html .= debug_map_html($grids);
      $ret_html .='<hr color="red"/><br/><br/><br/>'.PHP_EOL.PHP_EOL.PHP_EOL;  
    }
    $map_html_debug = $ret_html;
    return $ret_html;
}


$debug_map_html_id = 0;

function debug_map_html(&$grids){
    global $w, $h ,$debugMode , $debug_map_html_id;

    $cell_height = '30px';
    $cell_width = '30px';

    $debug_map_html_id++;
    $map_html = '<h3>DEBUG MAP TABLE #'.$debug_map_html_id.'</h3>';

    $map_html .='<table align="center" border="1" cellspacing="0" cellpadding="0" class="printtab"><tbody>'.PHP_EOL;
    
    $map_html .= '<tr height="'.$cell_height.'">'.PHP_EOL;
    $map_html .= '<td width="'.$cell_width.'" id="xytd">&nbsp;</td>'.PHP_EOL;
    for ($i=0; $i < $w; $i++) { 
      $map_html .= '<td width="'.$cell_width.'" id="xtd_'.$i.'">x:'.$i.'</td>'.PHP_EOL;
    }
    $map_html .= '</tr>'.PHP_EOL;

    for($y = 0; $y < $h; $y++ ){
        $map_html .= '<tr height="'.$cell_height.'">'.PHP_EOL;
        
        $map_html .= '<td width="'.$cell_width.'" id="ytd_'.$y.'">y:'.$y.'</td>'.PHP_EOL;

        for($x=0; $x < $w; $x++ ){
          $c='';
          $style='';
            if(isset($grids[$y * $w + $x])){
              $vv = $grids[$y * $w + $x];
              $arr = explode('#', $vv);
              $v =$arr[0]; 
              if(count($arr)>1){
                $c =$arr[1]; 
                $style=' style="background-color:#'.$c.'" ';  
              }              
            }else{
              $v = 'miss';              
            }
            $map_html .= '<td width="32px" id="td_'.$x.'_'.$y.'" '.$style.' >'.$v.'</td>'.PHP_EOL;
        }
        $map_html .= '</tr>'.PHP_EOL;
    }
    return $map_html.'</tbody></table>'.PHP_EOL;
}

function debug_init_map($w, $h){
  $tmp_grids = array();
  for ($y = 0; $y < $h; $y ++) {
    for ($x = 0; $x < $w; $x ++) {
      // array_push($tmp_grids, 0);
      // $v = $y * $w + $x;
      // array_push($tmp_grids, $v);
      array_push($tmp_grids, '&nbsp;');
    }
  }
  return $tmp_grids;
}


$all_func_name_arr = array();

function get_func_debug_mode($funcName){
  global $all_func_name_arr ,$debugMode;
  if(!$debugMode) return false;
  $func_name = strtolower(trim($funcName));
  // echo 'DEBUG: ' . __FUNCTION__ . '('.$func_name.')'. PHP_EOL;   
  if(!in_array($func_name, $all_func_name_arr)){
    array_push($all_func_name_arr, $func_name);
  }

  switch ($func_name) {
    case 'ksleaf::ksleaf':
      $ret = false;
      break;

    case 'ksleaf::set_color_config':
      $ret = false;
      break;
    
    case 'ksleaf::split':
      $ret = false;
      break;

    case 'ksleaf::_fill_map_with_rect': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::fillmaps': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::_bsp_rand_xy': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::createhall': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksleaf::createrooms': 
      // $ret = true;
      $ret = false;
      break;

    case 'ksbsp::bsp': 
      $ret = false;
      break;

    case 'get_color': 
      $ret = false;
      break;

    case 'convert_map_grids';
      $ret = false;
      break;

    default:
      $ret = true;
      break;
  }
  return $ret;
}


function map_color($id){
  switch ($id) {
    case 'leaf':
      return 1; //#dddddd
      break;

    case 'room':
      return 4; //#666666
      break;
    
    case 'hall':
      return 33; //#cc6600
      break;

    default:
      return false;   //随机颜色
      break;
  }

}

function get_top_color($pathSetId,$v,$k){
  //v=0;788#4;788#cc6600;788#1
  $max_cc = get_top_cell_color($v);
  if(strlen($max_cc)==6) return $cc;
  if($max_cc>0) 
    return get_color($max_cc);
  return get_color($pathSetId);
}

function get_top_cell_color($v){
  // global $color_config;
  // if($color_config){
  //   $tmpArr = explode(';', $color_config['sort']);
  //   $sortArr=array();
  //   foreach ($tmpArr as $key => $value) {
  //     if(isset($color_config[$value])){
  //       $sortArr[$value]=$key;
  //     }
  //   }
  // }
  //v=0;788#4;788#cc6600;788#1
  $mode=2;  
  if($mode==1){
    $max_cc = -1;
    $max_top = 999;    
  }else{
    $max_cc = 999;
    $max_top = -1;
  }

  if($v==='0') return $max_cc;

  $arr = explode(';', $v);  
  foreach ($arr as $key => $value) {
    if(stripos($value, '#')!==false){
      $arr2 = explode('#', $value);
      $cc = $arr2[count($arr2)-1];
      if(strlen($cc)==6) $cc = $max_top;
      if($mode==1){
        if($cc > $max_cc) $max_cc = $cc;
      }else{
        if($cc < $max_cc) $max_cc = $cc;
      }
    }
  }
  return $max_cc;  
}


?>
<?php

